package com.hong.concurrent.chapter16;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author csh
 * @Description
 * @Date 2018/7/10 21:05
 */
public class AppServer extends  Thread{
    /*端口*/
    private int port;
    /*默认值*/
    private static final int DEFAULT_PORT =12722;
    /*状态*/
    private volatile boolean start = true;
    /*工作线程*/
    private List<ClientHandler> clientHandlers = new ArrayList<ClientHandler>();

    /*线程池*/
    private final ExecutorService executor = Executors.newFixedThreadPool(10);


    private ServerSocket server;

    public AppServer() {
        this(DEFAULT_PORT);
    }
    /*初始化线程*/
    public AppServer(int port) {
        this.port = port;
    }

    public void shutdown() throws IOException {
        this.start = false;
        this.interrupt();
        this.server.close();
    }

    @Override
    public void run() {
        try {
            this.server = new ServerSocket(port);
            while (start){
                Socket client = server.accept();
                ClientHandler clientHandler = new ClientHandler(client);
                executor.submit(clientHandler);
                this.clientHandlers.add(clientHandler);
            }
        } catch (IOException e) {
     //       throw new RuntimeException(e);
        }finally {
            this.dispose();
        }
    }
    /*销毁*/
    private void dispose() {
        System.out.println("dispose");
        /*关闭socket*/
        this.clientHandlers.stream().forEach(ClientHandler::stop);
        //关闭线程池
        this.executor.shutdown();
    }
}
